"use strict"

/**
 * 部门管理
 * @param  {[type]} app      [description]
 * @param  {[type]} settings [description]
 * @return {[type]}          [description]
 */
module.exports = function(app, settings) {
	var debug = require('debug')('qywx-api'),
		express = require('express'),
		util = require('util'),
		url = require('url'),
		QywxAPI = require('../utils/QywxAPI')();

	var router = express.Router();
	/**
	 * 删除部门信息
	 */
	router.get("/delete", function(req, res, next) {

		let accessToken = res.locals.account.accessToken;
		let id = req.query.department_id;


		QywxAPI.deleteDepartment(accessToken, id,
			function(err, data) {
				if (err) {
					return res.status(500).json({
						success: false,
						errCode: 500,
						errMsg: err.message
					});
				}
				return res.status(200).json({
					success: true
				});
			});

	});
	/**
	 *  修改部门信息
	 */
	router.post('/update', function(req, res, next) {

		let accessToken = res.locals.account.accessToken;

		let name = req.body.name;
		let parentId = req.body.parent_id;
		let order = req.body.order || 100;
		let id = req.body.department_id;

		QywxAPI.updateDepartment(accessToken, id, name, parentId, order,
			function(err, data) {
				if (err) {
					return res.status(500).json({
						success: false,
						errCode: 500,
						errMsg: err.message
					});
				}
				return res.status(200).json({
					success: true,
					data: data
				});
			});

	});

	/**
	 * 添加部门
	 */
	router.post("/", function(req, res, next) {
		let accessToken = res.locals.account.accessToken;

		let name = req.body.name;
		let parentId = req.body.parent_id;
		let order = req.body.order || 100;
		let id = req.body.department_id;

		QywxAPI.createDepartment(accessToken, name, parentId, order, id,
			function(err, data) {
				if (err) {
					return res.status(500).json({
						success: false,
						errCode: 500,
						errMsg: err.message
					});
				}
				return res.status(200).json({
					success: true,
					data: data
				});
			});


	});
	/**
	 * 获取部门列表
	 */
	router.get("/", function(req, res, next) {
		let accessToken = res.locals.account.accessToken;
		let departmentId = req.query.department_id || 1;

		QywxAPI.getDepartmentList(accessToken, departmentId, function(err, data) {
			if (err) {
				return res.status(500).json({
					success: false,
					errCode: 500,
					errMsg: err.message
				});
			}

			return res.status(200).json({
				success: true,
				data: data
			});
		});
	});

	app.use('/departments', router);
}